<template>
  <div id="login">
    <ParticlesBg type="thick" :bg="true" />
      <div class="form-area">
        <ul class="tabs">
          <li :class="['tabs-item', {'current': item.status}]" v-for="(item,index) in menuTabs" :key="item.txt" @click="toggleTab(index)">{{item.txt}}</li>
      </ul>
      <div class="form-wrap">
          <el-form ref="form" :model="form" label-width="80px" label-position="top" :rules="rules">
  <el-form-item label="用户名" prop="username">
    <el-input v-model="form.username"></el-input>
  </el-form-item>
   <el-form-item label="密码" prop="password">
    <el-input v-model="form.password" type="password"></el-input>
  </el-form-item>
   <el-form-item label="确认密码" v-if="menuTabs[1].status" prop="rePassword">
    <el-input v-model="form.rePassword" type="password"></el-input>
  </el-form-item>
   <el-form-item label="验证码" class="valid-code-row" prop="validCode">
       <el-row :gutter="10">
           <el-col :span="15">
               <el-input v-model="form.validCode"></el-input>
           </el-col>
           <el-col :span="9">
               <el-button  type="primary" @click="getSms" :disabled="!validCodeBtn.status" :loading="validCodeBtn.loading">{{ validCodeBtn.text }}</el-button>
           </el-col>
       </el-row>
  </el-form-item>
  <el-form-item>
    <el-button type="success" class="submit-btn" @click="submitForm">{{menuTabs[0].status ? '登录' : '注册'}}</el-button>
  </el-form-item>
          </el-form>
      </div>
      </div>
  </div>
</template>

<script>
import { reactive, onMounted } from '@vue/composition-api'
import { emailVailtor, specialCharVaildator, passwordValidator } from '../../utils/validator.js'
import { getSmsRequest, registerRequest } from '@/api/login.js'
import sha1 from 'js-sha1'
import { ParticlesBg } from 'particles-bg-vue'
// import myAxios from '@/utils/request'
export default {
  components: {
    ParticlesBg
  },
  // setup函数代替beforeCreated 和 created生命周期函数
  // props是属性值 context是该组件对象
  setup (props, context) {
    // 验证邮箱
    var validateUsername = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入用户名'))
      } else if (!emailVailtor(value)) {
        return callback(new Error('请输入合法用户名'))
      }
      callback()
    }
    var validatePassword = (rule, value, callback) => {
      value = specialCharVaildator(value)
      form.password = value
      if (!value) {
        return callback(new Error('请输入密码'))
      } else if (!passwordValidator(value)) {
        return callback(new Error('请输入6位到20位的字母与数字'))
      }
      callback()
    }
    // 验证两次密码
    var checkPass = (rule, value, callback) => {
      console.log(value)
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== form.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    // 数据
    // 使用reactive方法声明一个复炸数据类型的数据 传入一个初始值
    const form = reactive({
      username: '',
      password: '',
      validCode: ''
    })
    const rules = reactive({
      username: [
        { validator: validateUsername, trigger: 'blur' }
      ],
      password: [
        { validator: validatePassword, trigger: 'blur' }
      ],
      rePassword: [
        { validator: checkPass, trigger: 'blur' }
      ],
      validCode: [{
        required: true, message: '请输入验证码', trigger: 'blur'
      }, {
        min: 6, message: '请输入6位验证码', trigger: 'blur'
      }, {
        max: 6, message: '请输入6位验证码', trigger: 'blur'
      }]
    })
    const menuTabs = reactive([{
      txt: '登录',
      status: true
    }, {
      txt: '注册',
      status: false
    }])
    // 验证码按钮信息
    const validCodeBtn = reactive({
      text: '获取验证码',
      status: true,
      loading: false,
      module: 'login'
    })
    // 方法
    const toggleTab = (i) => {
      menuTabs.forEach((item, index) => {
        if (index === i) {
          item.status = true
        } else {
          item.status = false
        }
      })
      validCodeBtn.module = i === 0 ? 'login' : 'register'
      console.log(validCodeBtn.module)
      context.refs.form.resetFields()
    }
    // 提交表单
    const submitForm = () => {
      context.refs.form.validate(async (valid) => {
        if (valid) {
          const requestParams = {
            username: form.username,
            password: sha1(form.password),
            code: form.validCode
          }
          if (menuTabs[0].status) {
            // 登录
            const res = await context.root.$store.dispatch('account/login', requestParams)
            console.log(res)
            context.root.$message({
              message: res.message,
              type: 'success'
            })
            context.root.$router.push('/console')
          } else {
            // 注册表单提交
            const { data: res } = await registerRequest(requestParams).catch(err => err)
            context.root.$message({
              message: res.message,
              type: 'success'
            })
            toggleTab(0)
          }
        } else {
          return false
        }
      })
    }
    // 获取验证码
    const getSms = () => {
      if (!form.username.trim()) {
        return context.root.$message({
          message: '请先输入邮箱',
          type: 'warning'
        })
      }
      if (!emailVailtor(form.username)) {
        return context.root.$message({
          message: '请输入合法邮箱',
          type: 'warning'
        })
      }
      const requestParams = {
        username: form.username,
        module: validCodeBtn.module
      }
      validCodeBtn.text = '正在获取'
      validCodeBtn.loading = true
      getSmsRequest(requestParams).then(res => {
        context.root.$message({
          message: res.data.message,
          type: 'success'
        })
        console.log(res)
        validCodeBtn.status = false
        validCodeBtn.loading = false
        countDown()
      }).catch(err => {
        validCodeBtn.text = '重新获取'
        validCodeBtn.status = true
        validCodeBtn.loading = false
        console.log(err)
      })
    }
    var timerId = 0
    var leftTime = 5
    const countDown = () => {
      validCodeBtn.text = `${leftTime}秒后`
      timerId = setInterval(() => {
        leftTime--
        if (leftTime <= 0) {
          leftTime = 5
          clearInterval(timerId)
          validCodeBtn.status = true
          validCodeBtn.text = '重新获取'
          return
        }
        validCodeBtn.text = `${leftTime}秒后`
      }, 1000)
    }
    // 生命周期
    onMounted(() => {

    })
    // 最后要把数据和方法return出去
    return {
      form,
      rules,
      menuTabs,
      toggleTab,
      submitForm,
      getSms,
      validCodeBtn
    }
  }
}
</script>

<style lang="scss">
    #login {
        height: 100%;
        padding-top: 100px;
    .form-area {
        width: 330px;
        margin: 0 auto;
        .tabs {
            text-align: center;
            .tabs-item {
                display: inline-block;
                width: 80px;
                line-height: 36px;
                color: #fff;
                font-size: 12px;
                border-radius: 2px;
                cursor: pointer;
            }
            .current {
                background-color: rgba(255,255,255,.5);
            }
        }
       }
       .form-wrap {
           .el-form-item {
               label {
               padding: 0;
               font-size: 12px;
               color: #fff;
           }
           }
           .submit-btn {
               width: 100%;
           }
           .valid-code-row {
               margin-bottom: 20px;
           }
       }
    }
</style>
